import json
import sys

import requests
from bs4 import BeautifulSoup
from googletrans import Translator
from PyQt5 import QtCore
from PyQt5.QtGui import QIcon, QTextCursor
from PyQt5.QtWidgets import (QApplication, QPushButton,
                             QTextEdit, QVBoxLayout, QTextBrowser,
                             QWidget)


#自定义Textedit以便实现取词功能
class myTextedit(QTextEdit):
    
    def __init__(self, parent=None):
        super(myTextedit, self).__init__(parent)
        self.__baseUrl = 'http://www.iciba.com/'  # 爱词霸的单词查询链接
        self.__header = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36'}
    
    # 抽取单词的具体信息
#    def extraWordInfo(self, text):
#        urlInfo = json.loads(text)
#        wordDefs = urlInfo['defs']
#        poses = []
#        defs = []
#        if wordDefs is not None:
#            for item in wordDefs:
#                poses.append(item['pos'])
#                defs.append(item['def'])
#
#        return poses, defs

    def showWord(self):
        text_coursor = self.textCursor()
        text_coursor.select(QTextCursor.WordUnderCursor)
        selectedText = text_coursor.selectedText()

        if len(selectedText) > 1 and selectedText[0] >= 'A' and selectedText[0] <= 'z':
            wordUrl = self.__baseUrl + selectedText
            try:
                r = requests.get(wordUrl,headers = self.__header)
                r.encoding = r.apparent_encoding
                soup = BeautifulSoup(r.text,'html.parser')
                print(soup)
                word_info = soup.find('ul','').text
                word_info = word_info.replace('\n\n','\n')
            except:
                word_info = ''
            
            self.setToolTip(word_info)

    def mousePressEvent(self, e):
        if e.buttons() == QtCore.Qt.LeftButton:
            pos = e.pos()
            coursor = self.cursorForPosition(pos)
            self.setTextCursor(coursor)
            self.showWord()

class CopyTranslator(QWidget):
    def __init__(self):
        super().__init__()

        self.__translator = Translator(service_urls=['translate.google.cn'])
        self.__src = 'en'
        self.__dest = 'zh-cn'
        self.initUI()

    def initUI(self):
        self.__TextC = QTextBrowser() #中文翻译文本框
        self.__TextE = myTextedit() #英文文本框
        transButton = QPushButton('Translate')

        VBox = QVBoxLayout()

        VBox.addWidget(self.__TextE)
        VBox.addWidget(transButton)
        VBox.addWidget(self.__TextC)

        self.__TextE.setFontPointSize(12)
        self.__TextC.setFontPointSize(12)
        self.__TextE.setMouseTracking(True)

        transButton.clicked.connect(self.translate)

        self.setLayout(VBox)

        self.setGeometry(300, 300, 600, 650)
        self.setWindowTitle('CopyTranslate')
        self.setWindowIcon(QIcon('images/image.ico'))
        self.show()
    
    # 格式化文本
    @staticmethod
    def format_text(text):
        text = text.replace('-\n', '')
        text = text.replace('\n', ' ')
        
        return text


    # 格式化文本并调用谷歌翻译翻译文字段落
    def translate(self):
        srcText = self.__TextE.toPlainText()
        srcText = self.format_text(srcText)
        self.__TextE.setText(srcText)
        try:
            destText = self.__translator.translate(
                srcText, src=self.__src, dest=self.__dest).text
        except:
            destText = '无法连接谷歌翻译'
        self.__TextC.setText(destText)


    # 显示单词的具体信息
#     def showWord(self):
#         text_coursor = self.__TextE.textCursor()
#         text_coursor.select(QTextCursor.WordUnderCursor)
#         selectedText = text_coursor.selectedText()
# 
#         if len(selectedText) > 1 and selectedText[0] >= 'A' and selectedText[0] <= 'z':
#             wordUrl = self.__baseUrl + selectedText
#             r = requests.get(wordUrl)
#             r.encoding = r.apparent_encoding
#             poses, defs = self.extraWordInfo(r.text)
#             shownText = selectedText + '\n'
#             if defs is not None:
#                 for (pos, wordDef) in zip(poses, defs):
#                     shownText = shownText + pos + '\n' + wordDef + '\n\n'
# 
#             self.__TextE.setToolTip(shownText)


if __name__ == '__main__':

    app = QApplication(sys.argv)
    trans = CopyTranslator()
    sys.exit(app.exec_())
